﻿using System;
using System.Collections.Generic;
using System.Text;
using Lidgren.Network;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ObjectSync.Util
{
    public static class Syncronization
    {
        public static void DecodeMessageAndSync(NetIncomingMessage Message)
        {
            DecodeMessageAndSync(Message, false);
        }
        public static void DecodeMessageAndSync(NetIncomingMessage Message, bool server)
        {
            // Let´s first rebuild our struture
            //List<SyncData> TList = new List<SyncData>();

            int numberofObjects = Message.ReadInt32();

            for (int i = 0; i < numberofObjects; i++)
            {
                SyncData transData = new SyncData {
                    PropertiesValues = new List<object>(), 
                    PropertiesNames = new List<string>(), 
                    oid = Message.ReadInt32() };

                int numberofProperties = Message.ReadInt32();

                for (int z = 0; z < numberofProperties; z++)
                {
                    string propName = Message.ReadString();
                    Int32 propertySerializedSize = (int)Message.ReadInt64();
                    byte[] propSerialized = Message.ReadBytes(propertySerializedSize);
                    
                    BinaryFormatter formatter = new BinaryFormatter();

                    MemoryStream ms = new MemoryStream(propSerialized);
                    transData.PropertiesNames.Add(propName);
                    transData.PropertiesValues.Add(formatter.Deserialize(ms));
                    
                }
                SyncManager.Instance.AplyChangesToObjects(transData, server);
            }

        }
    }
}
